package com.xu.common.qiNiu;

import cn.hutool.core.util.URLUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.xu.common.exception.MyException;
import org.springframework.stereotype.Component;

/**
 * 七牛云工具类
 *
 * @author xu
 * 2022/7/22 11:20
 */
@Component
public record QiNiuUtil(QiNiuProperty qiNiuProperty,
                        Auth auth,
                        BucketManager bucketManager,
                        UploadManager uploadManager) {

    /**
     * 返回域名加文件名
     */
    public String uploadFile(byte[] bytes, String fileName) throws QiniuException {
        String token = auth.uploadToken(qiNiuProperty.getBucketName());
        Response res = uploadManager.put(bytes, fileName, token);
        if (!res.isOK()) {
            throw new MyException("上传七牛云出错:" + res);
        }
        return URLUtil.normalize(qiNiuProperty.getPrefix() + "/" + fileName);
    }

    /**
     * 域名加文件名
     */
    public void deleteFile(String prefixFileName) throws QiniuException {
        // 获取文件名 之所以 +8  是因为还要去除 http:// 以及 /
        String fileName = prefixFileName.substring(qiNiuProperty.getPrefix().length()+8);
        bucketManager.delete(qiNiuProperty.getBucketName(), fileName);
    }

    public static void main(String[] args) {
        String prefixFile = "http://cdn.xuwang.info/blog/3.jpg";

        String a = "cdn.xuwang.info";

        String fileName = prefixFile.substring(a.length()+8);

        System.out.println(fileName);

        System.out.println(URLUtil.normalize(a));
    }
}
